package x.socket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;

public class MyMessage  extends MessageInbound {

    private final String nickname;

    public MyMessage(String nickname) {
        this.nickname = nickname;
    }

    @Override
    public void onOpen(WsOutbound outbound) {
        Utils.connections.add(this);
        String message = String.format("* %s %s",
                nickname, "has joined.");
        sendMsg(message);
    }

    @Override
    public void onClose(int status) {
    	Utils.connections.remove(this);
        String message = String.format("* %s %s",
                nickname, "has disconnected.");
        sendMsg(message);
    }

    @Override
    public void onBinaryMessage(ByteBuffer message) throws IOException {
        throw new UnsupportedOperationException(
                "Binary message not supported.");
    }

    @Override
    public void onTextMessage(CharBuffer message) throws IOException {
        // Never trust the client
        String filteredMessage = String.format("%s: %s",
                nickname, Utils.htmlFilter(message.toString()));
        sendMsg(filteredMessage);
    }

    public void sendMsg(String message) {
        for (MyMessage connection : Utils.connections) {
            try {
                CharBuffer buffer = CharBuffer.wrap(message);
                connection.getWsOutbound().writeTextMessage(buffer);
            } catch (IOException ignore) {
                // Ignore
            }
        }
    }
}
